package com.item.audrey_hepburn.controller.db2;/*/**

 _______  _______________   _________________________  __________ ____ ___  ________ 
 \      \ \_   _____/\   \ /   /\_   _____/\______   \ \______   \    |   \/  _____/ 
 /   |   \ |    __)_  \   Y   /  |    __)_  |       _/  |    |  _/    |   /   \  ___ 
/    |    \|        \  \     /   |        \ |    |   \  |    |   \    |  /\    \_\  \
\____|__  /_______  /   \___/   /_______  / |____|_  /  |______  /______/  \______  /
        \/        \/                    \/         \/          \/                 \/ 
 
 * @Auther: WD
 * @Date: 19-5-3 10:54
 * @Description: 
 */


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.item.audrey_hepburn.Enum.CityEnum;
import com.item.audrey_hepburn.base.BaseController;
import com.item.audrey_hepburn.entity.db2.Ticket;
import com.item.audrey_hepburn.entity.db2.TicketNum;
import com.item.audrey_hepburn.entity.db2.User;
import com.item.audrey_hepburn.mapper.db2.CityMapper;
import com.item.audrey_hepburn.service.AsyncTaskService;
import com.item.audrey_hepburn.util.SessionUtil;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;


@Controller
@RequestMapping("/ticketGrabbingController")
public class TicketGrabbingController extends BaseController<CityMapper> {

    @Autowired
    private AsyncTaskService asyncTaskService;



    /**
     * @描述 跳转抢票页面
     * @参数 []
     * @返回值 java.lang.String
     * @创建人 wangdong
     * @创建时间 19-5-3/上午11:03
     * @修改人和其它信息
     */


    @RequestMapping(value = "/goToPage", method = RequestMethod.GET)
    public String goToPage() {
       /* mv.setViewName("/ticketGrabbing/ticketGrabbing");
        return mv;*/
       return  "ticketGrabbing/ticketGrabbing";
    }
    /**

     *@描述 测试接口

     *@参数  [request]

     *@返回值  java.lang.Object

     *@创建人  wangdong

     *@创建时间  19-5-7/下午9:37

     *@修改人和其它信息

     */
    @RequestMapping(value = "/getInfo",method = RequestMethod.GET)
    @ResponseBody
    public Object getInfo(HttpServletRequest request
            /*@RequestParam(value="start") String start,
            @RequestParam(value="end") String end,
            @RequestParam(value="time") String time*/
            )throws Exception {
        logger.info("出发地："+request.getParameter("start"));
        /*logger.info("终点站："+end);
        logger.info("时间 ："+time);*/
        HttpResponse response = HttpRequest
                .get("https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=2019-05-16&leftTicketDTO.from_station=TXK&leftTicketDTO.to_station=SHH&purpose_codes=ADULT")
                .send();
        String data = getISO8859ToUtf8(response.bodyText().toString());
        logger.info("获取数据："+data);

        if(null==data){
            return null;
        }
        return getStringToJsonObject(data).toString();

    }

    /**

     *@描述 查询车票信息

     *@参数  [request, start, end, time]

     *@返回值  java.lang.Object

     *@创建人  wangdong

     *@创建时间  19-5-7/下午9:37

     *@修改人和其它信息

     */
    @RequestMapping(value = "/testInfo",method = RequestMethod.GET)
    @ResponseBody
    public Object testInfo(HttpServletRequest request,
                           @RequestParam(value = "start") String start,
                           @RequestParam(value = "end") String end,
                           @RequestParam(value = "time") String time
                           )throws Exception {

        logger.info("来到这里了"+start+","+end+","+time);

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=");
        stringBuilder.append(time);
        stringBuilder.append("&leftTicketDTO.from_station=");
        stringBuilder.append(CityEnum.getByCode(start));
        stringBuilder.append("&leftTicketDTO.to_station=");
        stringBuilder.append(CityEnum.getByCode(end));
        stringBuilder.append("&purpose_codes=ADULT");
        HttpResponse response = HttpRequest
                .get(stringBuilder.toString())
                .queryEncoding("CP1251")
                .send();
        //JsonObject jsonObject = new BaseController().getStringToJsonObject("");
        // System.out.println(response.toString().replaceAll("u007C","haha"));
        String zifu = response.bodyText().toString();
        JSONObject resultData = new JSONObject();
        JSONObject jsonObject = JSON.parseObject(zifu);

        //JsonObject jsonObject = new BaseController().getStringToJsonObject(zifu);
        //jsonObject.getAsJsonObject();
        JSONObject data =jsonObject.getJSONObject("data");
        JSONArray results = data.getJSONArray("result");

        List<Ticket>tickets=new ArrayList<>();
        Ticket ticket =null;
        for(int i=0;i<results.size();i++){
            String result = results.get(i).toString();
            //System.out.println(result);

            String TrainNumber = result.split("\\|")[3];
            String[] datas = result.split("\\|");
            if(TrainNumber.split("")[0].equals("K")){
                String[] TicketType = result
                        .split("\\|\\|\\|\\|")[1]
                        .replaceAll("\\|\\|\\|","\\|")
                        .replaceAll("\\|\\|","\\|")
                        .split("\\|");


                ticket = new Ticket
                        .Builder()
                        .setTRAINNUMBER(TrainNumber)
                        .setTICKETTYPE("火车票")
                        .setSTART(datas[6])
                        .setEND(datas[7])
                        .setSTARTTIME(datas[8])
                        .setENDTIME(datas[9])
                        .setUSETIME(datas[10])
                        .setHIGHGRADESOFTBERTH(null)
                        .setORDINARYSOFTSLEEPER(TicketType[0])
                        .setHARDSLEEPER(TicketType[2])
                        .setSOFTSEATS(null)
                        .setHARDSEAT(TicketType[3])
                        .setNOSEAT(TicketType[1])
                        .setBUSINESSBLOCK(null)
                        .setFIRSTCLASSSEAT(null)
                        .setSECONDCLASSSEAT(null)
                        .builder()
                ;
                tickets.add(ticket);
                System.out.println("火车："+ticket.toString());

            }else if(TrainNumber.split("")[0].equals("G")){

                ticket =
                        new Ticket
                                .Builder()
                                .setTRAINNUMBER(TrainNumber)
                                .setTICKETTYPE("高铁票")
                                .setSTART(datas[6])
                                .setEND(datas[7])
                                .setSTARTTIME(datas[8])
                                .setENDTIME(datas[9])
                                .setUSETIME(datas[10])
                                .setHIGHGRADESOFTBERTH(null)
                                .setORDINARYSOFTSLEEPER(null)
                                .setHARDSLEEPER(null)
                                .setSOFTSEATS(null)
                                .setHARDSEAT(null)
                                .setNOSEAT(null)
                                .setBUSINESSBLOCK(datas[32])
                                .setFIRSTCLASSSEAT(datas[31])
                                .setSECONDCLASSSEAT(datas[30])
                                .builder()
                ;
                tickets.add(ticket);
                //System.out.println("高铁："+ticket.toString());


            }else if(TrainNumber.split("")[0].equals("D")){
                ticket =
                        new Ticket
                                .Builder()
                                .setTRAINNUMBER(TrainNumber)
                                .setTICKETTYPE("动车票")
                                .setSTART(datas[6])
                                .setEND(datas[7])
                                .setSTARTTIME(datas[8])
                                .setENDTIME(datas[9])
                                .setUSETIME(datas[10])
                                .setHIGHGRADESOFTBERTH(null)
                                .setORDINARYSOFTSLEEPER(null)
                                .setHARDSLEEPER(null)
                                .setSOFTSEATS(null)
                                .setHARDSEAT(null)
                                .setNOSEAT(null)
                                .setBUSINESSBLOCK(datas[32])
                                .setFIRSTCLASSSEAT(datas[31])
                                .setSECONDCLASSSEAT(datas[30])
                                .setHIGHGRADESOFTBERTH(datas[33])
                                .builder()
                ;
                tickets.add(ticket);
                //System.out.println("动车："+ticket.toString());


            }else{
                String[] TicketType = result
                        .split("\\|\\|\\|\\|")[1]
                        .replaceAll("\\|\\|\\|","\\|")
                        .replaceAll("\\|\\|","\\|")
                        .split("\\|");


                ticket = new Ticket
                        .Builder()
                        .setTRAINNUMBER(TrainNumber)
                        .setTICKETTYPE("火车票")
                        .setSTART(datas[6])
                        .setEND(datas[7])
                        .setSTARTTIME(datas[8])
                        .setENDTIME(datas[9])
                        .setUSETIME(datas[10])
                        .setHIGHGRADESOFTBERTH(null)
                        .setORDINARYSOFTSLEEPER(TicketType[0])
                        .setHARDSLEEPER(TicketType[2])
                        .setSOFTSEATS(null)
                        .setHARDSEAT(TicketType[3])
                        .setNOSEAT(TicketType[1])
                        .setBUSINESSBLOCK(null)
                        .setFIRSTCLASSSEAT(null)
                        .setSECONDCLASSSEAT(null)
                        .builder()
                ;
                tickets.add(ticket);
                System.out.println("火车："+ticket.toString());
            }

        }
        System.out.println(tickets.toString());
        resultData.put("code",1479);
        resultData.put("msg","ok");
        resultData.put("count",tickets.size());
        resultData.put("data",tickets);
        return resultData;
    }
    /**

     *@描述 抢票功能
     *     注：页面刷新功能改进

     *@参数  [start, end, time, trainnumber, tickettype, selectTs]

     *@返回值  java.lang.Object

     *@创建人  wangdong

     *@创建时间  19-5-8/下午10:30

     *@修改人和其它信息

     */
    @RequestMapping(value = "/bookTicket",method = RequestMethod.GET)
    @ResponseBody
    public Object bookTicket(
                            @RequestParam(value = "start") String start,
                            @RequestParam(value = "end") String end,
                            @RequestParam(value = "time") String time,
                            @RequestParam(value = "trainnumber") String trainnumber,
                            @RequestParam(value = "tickettype") String tickettype,
                            @RequestParam(value = "selectTs") String selectTs


                            )throws Exception{

        System.out.println("获取数据："+((User)SessionUtil.getSession().getAttribute("user")).getEmail());

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=");
        stringBuilder.append(time);
        stringBuilder.append("&leftTicketDTO.from_station=");
        stringBuilder.append(CityEnum.getByCode(start));
        stringBuilder.append("&leftTicketDTO.to_station=");
        stringBuilder.append(CityEnum.getByCode(end));
        stringBuilder.append("&purpose_codes=ADULT");
        HttpResponse response = HttpRequest
                .get(stringBuilder.toString())
                .queryEncoding("CP1251")
                .send();
        //JsonObject jsonObject = new BaseController().getStringToJsonObject("");
        // System.out.println(response.toString().replaceAll("u007C","haha"));
        String zifu = response.bodyText().toString();
        JSONObject resultData = new JSONObject();
        JSONObject jsonObject = JSON.parseObject(zifu);
        JSONObject data =jsonObject.getJSONObject("data");
        JSONArray jsonArray = data.getJSONArray("result");


        System.out.println(start+","+end+","+time+","+tickettype+","+trainnumber+","+selectTs);


        String[] selectT = selectTs.split(",");
        if(selectT.length<1)return "no";
        for (String s:
                selectT) {
            logger.info("这是车座类型："+s);
        }
        asyncTaskService.asyncTicketGrabbing(((User)SessionUtil.getSession().getAttribute("user")).getEmail(),selectT,jsonArray,trainnumber,tickettype);


        //---获取结果---
        //System.out.println(start+","+end+","+time+","+tickettype+","+trainnumber+","+selectTs);
        //Future<String> future = asyncTaskService.asyncInvokeReturnFuture(1);

        /*while (true){
            if(future.isDone()){
                logger.info("线程返回结果1:"+future.get());
                break;
            }
        }

        logger.info("线程返回结果2:"+future);*/
        return "ok";
    }

    public void huoChe(){

    }




    public static void main(String[] args) throws Exception {
        HttpResponse response = HttpRequest
                .get("https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=2019-05-06&leftTicketDTO.from_station=JNK&leftTicketDTO.to_station=QDK&purpose_codes=ADULT")
                .queryEncoding("CP1251")
                .send();
        //JsonObject jsonObject = new BaseController().getStringToJsonObject("");
       // System.out.println(response.toString().replaceAll("u007C","haha"));
        String zifu = response.bodyText().toString();

        JSONObject jsonObject = JSON.parseObject(zifu);

        //JsonObject jsonObject = new BaseController().getStringToJsonObject(zifu);
        //jsonObject.getAsJsonObject();
        JSONObject data =jsonObject.getJSONObject("data");
        JSONArray results = data.getJSONArray("result");

        List<Ticket>tickets=new ArrayList<>();
        Ticket ticket =null;
        for(int i=0;i<results.size();i++){
           String result = results.get(i).toString();
           //System.out.println(result);

           String TrainNumber = result.split("\\|")[3];
           String[] datas = result.split("\\|");
           if(TrainNumber.split("")[0].equals("K")){
               String[] TicketType = result
                       .split("\\|\\|\\|\\|")[1]
                       .replaceAll("\\|\\|\\|","\\|")
                       .replaceAll("\\|\\|","\\|")
                       .split("\\|");




               ticket = new Ticket
                               .Builder()
                               .setTRAINNUMBER(TrainNumber)
                               .setTICKETTYPE("火车票")
                               .setSTART(datas[6])
                               .setEND(datas[7])
                               .setSTARTTIME(datas[8])
                               .setENDTIME(datas[9])
                               .setUSETIME(datas[10])
                               .setHIGHGRADESOFTBERTH(null)
                               .setORDINARYSOFTSLEEPER(TicketType[0])
                               .setHARDSLEEPER(TicketType[2])
                               .setSOFTSEATS(null)
                               .setHARDSEAT(TicketType[3])
                               .setNOSEAT(TicketType[1])
                               .setBUSINESSBLOCK(null)
                               .setFIRSTCLASSSEAT(null)
                               .setSECONDCLASSSEAT(null)
                               .builder()
                       ;
               tickets.add(ticket);
               //System.out.println("火车："+ticket.toString());

           }else if(TrainNumber.split("")[0].equals("G")){

                ticket =
                       new Ticket
                               .Builder()
                               .setTRAINNUMBER(TrainNumber)
                               .setTICKETTYPE("高铁票")
                               .setSTART(datas[6])
                               .setEND(datas[7])
                               .setSTARTTIME(datas[8])
                               .setENDTIME(datas[9])
                               .setUSETIME(datas[10])
                               .setHIGHGRADESOFTBERTH(null)
                               .setORDINARYSOFTSLEEPER(null)
                               .setHARDSLEEPER(null)
                               .setSOFTSEATS(null)
                               .setHARDSEAT(null)
                               .setNOSEAT(null)
                               .setBUSINESSBLOCK(datas[32])
                               .setFIRSTCLASSSEAT(datas[31])
                               .setSECONDCLASSSEAT(datas[30])
                               .builder()
                       ;
               tickets.add(ticket);
               //System.out.println("高铁："+ticket.toString());


           }else if(TrainNumber.split("")[0].equals("D")){
                ticket =
                       new Ticket
                               .Builder()
                               .setTRAINNUMBER(TrainNumber)
                               .setTICKETTYPE("动车票")
                               .setSTART(datas[6])
                               .setEND(datas[7])
                               .setSTARTTIME(datas[8])
                               .setENDTIME(datas[9])
                               .setUSETIME(datas[10])
                               .setHIGHGRADESOFTBERTH(null)
                               .setORDINARYSOFTSLEEPER(null)
                               .setHARDSLEEPER(null)
                               .setSOFTSEATS(null)
                               .setHARDSEAT(null)
                               .setNOSEAT(null)
                               .setBUSINESSBLOCK(datas[32])
                               .setFIRSTCLASSSEAT(datas[31])
                               .setSECONDCLASSSEAT(datas[30])
                               .setHIGHGRADESOFTBERTH(datas[33])
                               .builder()
                       ;
               tickets.add(ticket);
               //System.out.println("动车："+ticket.toString());


           }

        }
        System.out.println(tickets.toString());
    }


    //列队学习：https://www.cnblogs.com/lemon-flm/p/7877898.html


    @RequestMapping("setTicketNum")
    public void setTicketNum() {
        TicketNum.getTicket().setValue("测试");
    }

    @RequestMapping("getTicketNum")
    @ResponseBody
    public Object getTicketNum() {
       return TicketNum.getTicket().toString();
    }
}
